package com.boboPlanet.filter;

import com.boboPlanet.comm.exception.BusinessException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @Description: TODO 自定义网关过滤器
 * @Author: mis_wu
 * @Date: 2023/6/20
 * @Company planet
 * 使用配置中添加 filters -Token （TokenGatewayFilterFactory XXXXGatewayFilterFactory）
 * 参照 StripPrefix
 **/
@Slf4j
@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomGatewayFilterFactory.Config> implements Ordered {

    public CustomGatewayFilterFactory(){
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        GatewayFilter gatewayFilter = (exchange, chain) -> {

            ServerHttpRequest request = exchange.getRequest();
            String requestPath = request.getURI().getPath();
            log.info("request into gateway customFilter, current path is: {}", requestPath);

            log.info("custom gateway filter param1: {}",config.requiredToken);

            log.info("custom gateway filter param2: {}",config.author);

            log.info("custom gateway filter param3: {}",config.desc);

            if (config.requiredToken){
                //1、获取请求头token信息
                List<String> requests = exchange.getRequest().getQueryParams().get("token");
                if (ObjectUtils.isEmpty(requests)){
                    throw BusinessException.build("非法令牌");
                }
                String token = requests.get(0);
                //do something...
            }
            return chain.filter(exchange);
        };

        log.info("into CustomGatewayFilterFactory, other operate judge in this here！！！");
        return new OrderedGatewayFilter(gatewayFilter, 10102);
    }

    /**
     * 用来配置filter时指定值 赋值给 Config中的哪个属性  yml中指定传参的顺序
     * @return List
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("requiredToken","author","desc");
    }

    @Override
    public int getOrder() {
        return 10102;
    }

    /**
     * 静态内部类 自定义配置类  可以传多个属性
     */
    @Data
    public static class Config{
        private boolean requiredToken;
        private String author;
        private String desc;
    }
}
